package com.shop.storage.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.shop.common.core.constant.CacheConstants;
import com.shop.common.core.utils.DateUtils;
import com.shop.common.core.utils.JwtUtils;
import com.shop.common.core.utils.StringUtils;
import com.shop.common.redis.service.RedisService;
import com.shop.common.security.utils.SecurityUtils;
import com.shop.storage.domain.*;
import com.shop.storage.service.IWmsPurchaseDetailService;
import com.shop.storage.vo.request.PurchaseAddRequest;
import com.shop.storage.vo.request.PurchaseRequest;
import com.shop.storage.vo.response.PurchaseDetailResponse;
import com.shop.storage.vo.response.PurchaseResponse;
import com.shop.system.domain.SysUser;
import com.shop.system.model.LoginUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shop.storage.mapper.WmsPurchaseMapper;
import com.shop.storage.service.IWmsPurchaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购信息Service业务层处理
 * 
 * @author shop
 * @date 2024-06-24
 */
@Service
@Log4j2
public class WmsPurchaseServiceImpl implements IWmsPurchaseService 
{
    @Autowired
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Autowired
    private IWmsPurchaseDetailService wmsPurchaseDetailService;

    @Autowired
    private WmsWareSkuServiceImpl wareSkuService;

    @Autowired
    private WmsForewarningServiceImpl wmsForewarningService;

    @Autowired
    private WmsPurchaseRequireServiceImpl wmsPurchaseRequireService;


    /**
     * 查询采购信息
     * 
     * @param id 采购信息主键
     * @return 采购信息
     */
    @Override
    public WmsPurchase selectWmsPurchaseById(Long id)
    {
        return wmsPurchaseMapper.selectWmsPurchaseById(id);
    }

    /**
     * 查询采购信息列表
     * 
     * @param wmsPurchase 采购信息
     * @return 采购信息
     */
    @Override
    public List<WmsPurchase> selectWmsPurchaseList(WmsPurchase wmsPurchase)
    {
        return wmsPurchaseMapper.selectWmsPurchaseList(wmsPurchase);
    }

    /**
     * 新增采购信息
     * 
     * @param wmsPurchase 采购信息
     * @return 结果
     */
    @Override
    public int insertWmsPurchase(WmsPurchase wmsPurchase)
    {
         wmsPurchase.setCreateTime(DateUtils.getNowDate());
        wmsPurchase.setUpdateTime(DateUtils.getNowDate());
        return wmsPurchaseMapper.insertWmsPurchase(wmsPurchase);
    }

    /**
     * 修改采购信息
     * 
     * @param wmsPurchase 采购信息
     * @return 结果
     */
    @Override
    public int updateWmsPurchase(WmsPurchase wmsPurchase)
    {
        Long userId = SecurityUtils.getUserId();
        wmsPurchase.setUpdateTime(DateUtils.getNowDate());
        wmsPurchase.setUpdateBy(String.valueOf(userId));
        int i = wmsPurchaseMapper.updateWmsPurchase(wmsPurchase);
        if (i > 0){
            //通过
            if (wmsPurchase.getStatus() == 4) {
                examine(wmsPurchase, 3L, 4L);
                return i;
            }
            //驳回
            if (wmsPurchase.getStatus() == 3) {
                examine(wmsPurchase, 4L, 3L);
                return i;
            }
            //入库
            if (wmsPurchase.getStatus() == 2) {
                bePutInStorage(wmsPurchase);
                return i;
            }
        }
        return i;
    }

    //通过或者驳回
    private void examine(WmsPurchase wmsPurchase, long status, long status1) {
        //查询详情
        List<PurchaseDetailResponse> purchaseDetailResponses = wmsPurchaseDetailService.purchaseDetailList();
        List<Long> list = new ArrayList<>();
        //遍历详情
        purchaseDetailResponses.forEach(itemDetail -> {
            //相同的改变
            if (wmsPurchase.getId().equals(itemDetail.getPurchaseId())) {
                //根据skuId去查找商品库存
                WmsWareSku wmsWareSku = wareSkuService.selectWmsWareSkuById(itemDetail.getSkuId());
                //改变预警表
                wmsForewarningService.updateWmsForewarningSkuId(wmsWareSku.getId(), status);
                //更改采购清单状态
                list.add(wmsWareSku.getId());
                wmsPurchaseRequireService.updateWmsPurchaseRequireWareSkuId(list, status1);
            }
        });
    }


    //如果状态为入库
    private void bePutInStorage(WmsPurchase wmsPurchase) {
        //查询详情
        List<PurchaseDetailResponse> purchaseDetailResponses = wmsPurchaseDetailService.purchaseDetailList();
        List<Long> list = new ArrayList<>();
        //遍历详情
        purchaseDetailResponses.forEach(itemDetail -> {
            //相同的改变
            if (wmsPurchase.getId().equals(itemDetail.getPurchaseId())){
                //根据skuId去查找商品库存
                WmsWareSku wmsWareSku = wareSkuService.selectWmsWareSkuById(itemDetail.getSkuId());
                //更改数量
                wmsWareSku.setStock(wmsWareSku.getStock() + itemDetail.getSkuNum());
                //改变库存数量
                wareSkuService.updateWmsWareSku(wmsWareSku);
                //改变预警表
                wmsForewarningService.updateWmsForewarningSkuId(wmsWareSku.getId(),5L);
                //更改采购清单状态
                list.add(wmsWareSku.getId());
                wmsPurchaseRequireService.updateWmsPurchaseRequireWareSkuId(list,5L);
            }
        });
    }


    /**
     * 批量删除采购信息
     * 
     * @param ids 需要删除的采购信息主键
     * @return 结果
     */
    @Override
    public int deleteWmsPurchaseByIds(Long[] ids)
    {
        return wmsPurchaseMapper.deleteWmsPurchaseByIds(ids);
    }

    /**
     * 删除采购信息信息
     * 
     * @param id 采购信息主键
     * @return 结果
     */
    @Override
    public int deleteWmsPurchaseById(Long id)
    {
        return wmsPurchaseMapper.deleteWmsPurchaseById(id);
    }

    /**
     * 查询采购信息列表
     *
     */
    @Override
    public List<PurchaseResponse> purchaseList(PurchaseRequest purchaseDetailDto) {
        //查询出采购信息
        List<PurchaseResponse> purchaseResponseList = wmsPurchaseMapper.purchaseList(purchaseDetailDto);
        //查询采购信息详情
        List<PurchaseDetailResponse> purchaseDetailResponseList = wmsPurchaseDetailService.purchaseDetailList();
        //循环采购信息
        purchaseResponseList.forEach(itemPurchase -> {
            //new 存放一个采购信息的集合
            List<PurchaseDetailResponse> purchaseResponses = new ArrayList<>();
            //循环采购信息详情
            purchaseDetailResponseList.forEach(itemPurchaseDetail -> {
                //把采购详情赋值到采购信息的集合
                if (itemPurchase.getId().equals(itemPurchaseDetail.getPurchaseId())){
                    purchaseResponses.add(itemPurchaseDetail);
                }
            });
            //把筛选出的数据赋值到采购信息
            itemPurchase.setPurchaseDetailResponses(purchaseResponses);
        });
        //返回
        return purchaseResponseList;
    }

    /**
     * 添加采购信息
     * @param purchaseAddRequest
     * @return
     */
    @Override
    @Transactional
    public int purchaseAdd(PurchaseAddRequest purchaseAddRequest) {
        //获取到现登录人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        //这个是要去添加的对象
        WmsPurchase wmsPurchase = new WmsPurchase();
        //采购人
        wmsPurchase.setAssigneeId(sysUser.getUserId());
        //采购人名称
        wmsPurchase.setAssigneeName(sysUser.getUserName());
        //采购人电话
        wmsPurchase.setPhone(sysUser.getPhonenumber());
        //总价
        wmsPurchase.setAmount(purchaseAddRequest.getRequireTotalPrices());
        //仓库id
        wmsPurchase.setWareId(1L);
        //供应商id
        wmsPurchase.setSupplierId(purchaseAddRequest.getSupplierId());
        insertPurchaseDetail(purchaseAddRequest, wmsPurchase);

        return 1;
    }


    //添加详情
    private void insertPurchaseDetail(PurchaseAddRequest purchaseAddRequest, WmsPurchase wmsPurchase) {
        int inserted = wmsPurchaseMapper.insertWmsPurchase(wmsPurchase);
        //循环传到后台的采购信息
        List<Long> list = new ArrayList<>();
        for (WmsPurchaseRequire wmsPurchaseRequire : purchaseAddRequest.getRequirementList()) {
            //查询库存列表
            WmsWareSku wmsWareSku = wareSkuService.selectWmsWareSkuById(wmsPurchaseRequire.getWareSkuId());
            //添加详情
            if (inserted > 0){
                //添加采购详情
                WmsPurchaseDetail wmsPurchaseDetail = new WmsPurchaseDetail();
                //采购id
                wmsPurchaseDetail.setPurchaseId(wmsPurchase.getId());
                //商品skuId
                wmsPurchaseDetail.setSkuId(wmsWareSku.getSkuId());
                //采购数量
                wmsPurchaseDetail.setSkuNum(wmsPurchaseRequire.getRequireSum());
                //总价
                wmsPurchaseDetail.setSkuPrice(wmsPurchaseRequire.getRequireTotalPrices());
                //仓库id
                wmsPurchaseDetail.setWareId(wmsWareSku.getWareId());
                //供应商id
                wmsPurchaseDetail.setSupplierId(purchaseAddRequest.getSupplierId());
                //添加商品详情
                wmsPurchaseDetailService.insertWmsPurchaseDetail(wmsPurchaseDetail);
                //
                list.add(wmsPurchaseRequire.getWareSkuId());

            }
        }
        //修改采购需求状态
        wmsPurchaseRequireService.updateWmsPurchaseRequireWareSkuId(list,2L);
    }




}
